<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\facade\Request;
use think\facade\Cache;

// 应用公共文件
/**
 * /**
 * 发送HTTP请求方法，目前只支持CURL发送请求
 * @param string $url 请求URL
 * @param array $params 请求参数
 * @param string $method 请求方法GET/POST
 * @param array $header
 * @return array  $data   响应数据
 * @throws \Exception
 */
function curl($url, $params = [], $method = 'GET', $header = [])
{
    $opts = [
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER     => $header
    ];

    /* 根据请求类型设置特定参数 */
    switch (strtoupper($method)) {
        case 'GET':
            if (!empty($params)) {
                $url .=  '?' . http_build_query($params);
            }
            $opts[CURLOPT_URL] = $url;
            break;
        case 'POST':
            //判断是否传输文件
            //$params                   = $params;
            $opts[CURLOPT_URL]        = $url;
            $opts[CURLOPT_POST]       = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new \Exception('不支持的请求方式！');
    }

    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data  = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) {
        throw new \Exception('请求发生错误：' . $error);
    }
    return $data;
}


/**
 * 实例化服务类
 * service('common/Order'); 实例化common模块的Order服务类
 * @param  string  $name 格式 [模块名]/接口名
 */
function service($name, $layer = '')
{
    if (!$name) {
        return false;
    }

    static $_service = [];

    $array     = explode('/', $name);
    $classname = array_pop($array);
    $module    = $array ? array_pop($array) : 'common'; // 默认是common分组下的service
    $class     = '\\app\\' . $module . '\\service\\' . $classname . ucfirst($layer);
    if (isset($_service[$class]) && is_object($_service[$class])) {
        return $_service[$class];
    }

    if (class_exists($class)) {
        $_service[$class] = new $class();
        return $_service[$class];
    }

    return false;
}

/**
 * 当前进程数限制
 * @param string $search 进程名称
 * @param int    $maxLimit 最大限制数[默认2]
 * @return boolean
 */
function ps_qty_limit($search, $maxLimit = 2)
{
    $result = '';
    exec("ps aux | grep '" . $search . "' | grep -v grep | awk '{ print  }' | head -50", $result);
    if (count($result) - 1 >= $maxLimit) {
        return false;
    } else {
        return true;
    }
}

/**
 *   随机字符串
 *@date: 2018年6月14日 上午9:55:50
 *@author: xxxxxxx
 * @param
 * @return string
 * @throws Exception
 */
function GetRandStr($len = 4)
{
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);
    $output = "";
    for ($i=0; $i<$len; $i++)
    {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}

/**
 * 控制器错误输格式化方法
 * @param $code
 * @param $msg
 * @param string $data
 * @return array
 */
function error_return($code, $msg, $data = '')
{
    return ['status' => 'error', 'code' => $code, 'msg' => $msg, 'data' => $data];
}

/**
 * 控制器正常输格式化方法
 * @param $data
 * @param string $code
 * @param string $msg
 * @return array
 */
function success_return($data, $code = '', $msg = '')
{
    return ['status' => 'success', 'code' => $code, 'msg' => $msg, 'data' => $data];
}

function sms($mobile,$type=1){
    require_once __DIR__ . '/../vendor/sms/SMS.php';
    return new \SMS($mobile,$type);
}

function general_sms($mobile, $content, $type = 1, $code = 0, $templateid = '213956')
{
  $smsOperator = new \wlwx\SmsOperator();

  $data1['destMobiles'] = $mobile;
  $data1['content'] = $content;
  $data1['templateid'] = $templateid;
  $data1['code'] = $code;
  $result = $smsOperator->send_comSms($data1);

  $data['phone'] = $mobile;
  $data['type'] = $type;
  $data['code'] = $code;
  $data['day'] = time();
  \app\common\model\SmsCode::create($data);

  return $result;
}

/**
 * [fileUrl description] 图片上传路劲前缀
 * @author Pan
 * @instruction
 * @DateTime    2018-06-11T14:12:36+0800
 * @param       [type]                   $url [description]  图片储存文件夹
 * @return      [type]                        [description]
 */
function file_url($url, $type = 'avatar'){
    $http = "http";
    if(isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === "on"){
        $http = "https";
    }

    $url = $http . '://' . request()->header('Host'). '/' . 'uploads'. '/' . $type . '/'  . $url;

    return $url;

}

/**
 * 创建目录
 */
function directory( $dir ){
   return  is_dir ( $dir ) or Directory(dirname( $dir )) and  mkdir ( $dir , 0777);
}

/**
 * 获取人名币美元汇率
 * @author Pan
 */
function get_exchange_rate()
{
    if (cache('rate')) {
        return cache('rate');
    }

    $url = "http://api.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=41229&sign=f903372f4d65edb6fc577558b2ac358b";
    // $ch = curl_init();
    // $timeout = 0;
    // curl_setopt ($ch, CURLOPT_URL, $url);
    // curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    // curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    // curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    // $rawdata = curl_exec($ch);
    // $rawdata = json_decode($rawdata, true);
    // curl_close($ch);
    // var_dump(curl_getinfo($ch),curl_error(),$rawdata);
    $rawdata = \http\Http::get($url);
    $rawdata = json_decode($rawdata, true);

    cache('rate', $rawdata['result']['rate'], 86400);
    return $rawdata['result']['rate'];
}

/**
 * 获取redis数据源对象
 * @return object
 */
function get_redis_obj() {
    static $redisObj;
    // 动态配置参数

    if (is_null($redisObj) || !is_object($redisObj)) {
        $redisObj = Cache::store('redis')->handler();
    }

    if (Request::isCli()) {
        try {
            $result = $redisObj->ping();
            $exist = strpos($result, 'PONG');
            if ($exist === false) {
                exception('Redis timeout and reconnecting!');
            }
        } catch (\think\Exception $e) {
            // 错误上报
            $redisObj = Cache::store('redis')->handler();
        }
    }

    return $redisObj;
}

/**
 * Log记录
 * @param string $message 输出信息
 * @return void
 */
function common_log($message, $exit = false) {
    $niceMsg = "[" . date("Y-m-d H:i:s") . "] " . $message . PHP_EOL;
    if (!Request::isCli()) {
        $niceMsg .= '<br/>';
    }
    echo $niceMsg;

    if ($exit) {
        exit();
    }
}
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

/**
 * 输出
 */
function pdie($arr,$type=false){
    if(!$type){
        echo "<pre>";
        print_r($arr);
        die();
    }else{
        echo "<pre>";
        var_dump($arr);
        die();
    }
}